package com.kuiandjie.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kuiandjie.entity.Employee;
import com.kuiandjie.service.EmployeeService;

public class AddEmpServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Employee em = (Employee) session.getAttribute("employee");
		
		if("tom".equals(em.getName())) {
			String method = request.getParameter("m");
			//判断是不是提交数据
			if(method == null || "".equals(method)){
				request.getRequestDispatcher("WEB-INF/views/addemp.jsp").forward(request, response);
			}else {
				//判断是不是post方法提交数据
				if("POST".equals(request.getMethod())){
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				
				//接收form表单传过来的数据
				String name = request.getParameter("name");
				String pwd = request.getParameter("pwd");
				//查看用户名是否被占用
				EmployeeService es = new EmployeeService();
				Employee e = es.getEmoloyeeByName(name);
				
				if(e == null){
					 es.addEmployee(name,pwd);
					 out.println("1");
					 out.flush();
					 out.close();
					
				}else{
					 out.println("2");
					 out.flush();
					 out.close();
					
				}
				//将新用户写进数据库
				
				
				
				}else {
					//get提交的数据报错
					response.sendError(405,"不支持get请求");
				}
			}
		}else{
			response.sendRedirect("main.jspx");
		}
	}
}
